package com.lora.communication.socket;

import com.lora.service.EntranceGuardService;
import com.lora.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SocketCmdInstance {

    private Map<String,Integer> count=new HashMap<>();

    @Autowired
    private EntranceGuardService entranceGuardService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private final Logger logger = LoggerFactory.getLogger(SocketCmdInstance.class);

    /**
     * 获取开门记录
     * @param eid
     * @param url
     * @param port
     * @return
     */
    public List<String> getLogs(String eid,String url,int port){
        try {
            String sn= StringUtil.fullzore(StringUtil.intToHex(Integer.parseInt(eid)));
            sn=getSn(sn);
            List<String> logs=new ArrayList<>();
            Socket socket=new Socket(url,port);
            OutputStream os = socket.getOutputStream();
            String str="17b40000"+sn+"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
            os.write(StringUtil.hexStringToByteArray(str));
            os.flush();
            InputStream is = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int len;
            String index="";
            while ((len = is.read(bytes)) != -1) {
                //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
                index = StringUtil.bytesToHexString(bytes);
                break;
            }
            Integer i = getIndex(eid);
            c:for (;; i++) {
                String indexnum= StringUtil.fullzore(StringUtil.intToHex(i));
                indexnum=indexnum.substring(6,8)+indexnum.substring(0,6);
                String cmd=StringUtil.fullzore_128("17b00000"+sn+indexnum);
                os.write(StringUtil.hexStringToByteArray(cmd));
                os.flush();
                String data="";
                int length=0;
                byte[] bytes1=new byte[2048];
                while ((length = is.read(bytes1)) != -1) {
                    //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
                    data = StringUtil.bytesToHexString(bytes1).substring(0,128);
                    if(Integer.parseInt(data.substring(16,18),16)==0){
                        count.put(eid,i);
                        break c;
                    }
                    logs.add(data);
                    count.put(eid,i);
                    break;
                }
            }
            os.close();
            socket.close();
            return logs;
        } catch (IOException e) {
            logger.error(e.getLocalizedMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取最新的开门记录
     * @param eid
     * @param url
     * @param port
     * @return
     */
    public String getLastRecord(String eid,String url,int port){
        try {
            String sn= StringUtil.fullzore(StringUtil.intToHex(Integer.parseInt(eid)));
            sn=getSn(sn);
            String logs=new String();
            Socket socket=new Socket(url,port);
            OutputStream os = socket.getOutputStream();
            InputStream is = socket.getInputStream();
            String cmd=StringUtil.fullzore_128("17b00000"+sn+"ffffffff");
            os.write(StringUtil.hexStringToByteArray(cmd));
            os.flush();
            String data="";
            int length=0;
            byte[] bytes1=new byte[2048];
            while ((length = is.read(bytes1)) != -1) {
                //注意指定编码格式，发送方和接收方一定要统一，建议使用UTF-8
                data = StringUtil.bytesToHexString(bytes1).substring(0,128);
                logs=data;
                break;
            }
            os.close();
            socket.close();
            return logs;
        } catch (IOException e) {
            logger.error(e.getLocalizedMessage());
            e.printStackTrace();
        }
        return null;
    }

    public void open(String eid,int door,String url,int port) throws IOException {
            String sn= StringUtil.fullzore(StringUtil.intToHex(Integer.parseInt(eid)));
            List<String> logs=new ArrayList<>();
            Socket socket= null;
            socket = new Socket(url,port);
            OutputStream os = socket.getOutputStream();
            sn=getSn(sn);
            String str="17400000"+sn+"0"+door+"00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
            os.write(StringUtil.hexStringToByteArray(str));
            os.flush();
            socket.close();
    }

    private String getSn(String str){
        return str.substring(6)+str.substring(4,6)+str.substring(2,4)+str.substring(0,2);
    }

    public Integer getIndex(String eid){
        String sql="select max(reasonno+0) as num from entrance_guard where sn = '"+eid+"'";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        if(maps!=null&&maps.size()>0&&maps.get(0).get("num")!=null){
            return Math.round(Float.parseFloat(maps.get(0).get("num").toString()))+1;
        }
        return 0;
    }
}
